package com.nosnow.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.nosnow.msm.service.MsmService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author by bingHeng
 * @version 1.0
 * @Create 2020/4/21 23:30
 */
@Service
public class MsmServiceImpl implements MsmService {

    @Override
    public boolean send(Map<String, Object> param, String phone) throws ClientException{
        // 1. 校验手机号是否为空
        if(StringUtils.isEmpty(phone)) {
            return false;
        }

        // TODO 阿里云的Id和秘钥后期整合到公共类中去，因为多个模块在使用
        // 2. 创建发送短信的对象
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4Fv9ww25yCmrju2UqTzf", "Ki997Hwd4UK5OakWbyd6rqSGHSFNln");
        IAcsClient client = new DefaultAcsClient(profile);

        // TODO 方法已过时，后期优化
        // 3. 设置相关参数
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 4. 设置发送相关参数
        request.putQueryParameter("PhoneNumbers", phone); // 手机号
        request.putQueryParameter("SignName", "snowflake好课网"); // 签名名称
        request.putQueryParameter("TemplateCode", "SMS_188635678"); // 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); // 验证码

        // 5. 最终发送
        CommonResponse response = client.getCommonResponse(request);
        return response.getHttpResponse().isSuccess();
    }
}
